<?php
/**
 * 
 * User class file
 * 
 * @author		Stijn Van Minnebruggen
 * @version		1.0.0
 * 
 */

class User
{

	/**
	 * Holds login status
	 * 
	 * @var		bool
	 */
	
	private $_loggedIn;
	
	
	/**
	 * Holds user data.
	 * 
	 * @var		array
	 */
	
	private $_data;
	
	
	/**
	 * Holds the session name.
	 * 
	 * @var		string
	 */
	
	private $_sessionName = 'cosa_user';
	
	
	/**
	 * Holds all available user languages for the user
	 * 
	 * @var		array
	 */
	
	public $_allowedLanguages;
	
	
	/**
	 * Initialise class
	 * 
	 * @return	void
	 */
	
	public function __construct()
	{
		// required
			global $cosa;
			session_start();
			$this->_loggedIn = false;
		
		// try to get user data
			if($cosa->system('installed')) {
				$this->_data = array();
				$this->checkSession();
			}
		
		// set user language if not set
			if(!isset($this->_data['language'])) $this->_data['language'] = DEFAULT_LANG;
		
	}
	
	
	/**
	 * Get the user id
	 * 
	 * @return	int
	 */
	
	public function __get($key)
	{
		return (isset($this->_data[$key])) ? $this->_data[$key] : false;
	}
	
	
	/**
	 * Get the user id
	 * 
	 * @return	int
	 */
	
	public function id()
	{
		return $this->_data['id'];
	}
	
	
	/**
	 * Check session.
	 * 
	 * @return bool
	 */
	
	private function checkSession()
	{
		global $cosa, $db;
		if(isset($_SESSION[$this->_sessionName])) {
			$s = split($this->_sessionName, $_SESSION[$this->_sessionName]);
			if(isset($s[0], $s[1])) {
				$sql = "SELECT id, uname, email, name_f, name_l, group_id, language_id FROM ".$db->table('users')." WHERE id = '".addslashes($s[0])."' LIMIT 1";
				$res = mysql_query($sql) or $cosa->kill('Database error in the user library.', 'db');
				if(mysql_num_rows($res)) {
					$user = mysql_fetch_array($res);
					if(md5(stripslashes($user['uname'])) == $s[1]) {
						$this->_loggedIn = true;
						$this->_data['id'] = stripslashes($user['id']);
						$this->_data['uname'] = stripslashes($user['uname']);
						$this->_data['email'] = stripslashes($user['email']);
						$this->_data['name_f'] = stripslashes($user['name_f']);
						$this->_data['name_l'] = stripslashes($user['name_l']);
						$this->_data['group_id'] = stripslashes($user['group_id']);
						$this->_data['language_id'] = stripslashes($user['language_id']);
						$this->getLanguages();
						return true;
					}
				}
			}
		}
		return false;
	}
	
	
	/**
	 * Log in
	 * 
	 * @param	string		$uname
	 * @param	string		$pass
	 * @return	bool
	 */
	
	public function login($uname, $pass)
	{
		global $cosa, $db;
		$sql = "SELECT id, uname, email, name_f, name_l, group_id, language_id FROM ".$db->table('users')." WHERE uname='".addslashes($uname)."' AND pass='".addslashes(md5($pass))."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->kill('Database error in the user library.', 'db');
		if(mysql_num_rows($res)) {
			$user = mysql_fetch_array($res);
			$_SESSION[$this->_sessionName] = $user['id'].$this->_sessionName.md5($user['uname']);
			$this->_loggedIn = true;
			$this->_data['id'] = stripslashes($user['id']);
			$this->_data['uname'] = stripslashes($user['uname']);
			$this->_data['email'] = stripslashes($user['email']);
			$this->_data['name_f'] = stripslashes($user['name_f']);
			$this->_data['name_l'] = stripslashes($user['name_l']);
			$this->_data['group_id'] = stripslashes($user['group_id']);
			$this->_data['language_id'] = stripslashes($user['language_id']);
			$this->updateTimeLastLogin();
			return true;
		} else return false;
	}
	
	
	/**
	 * Update time last login
	 * 
	 * @return	void
	 */
	
	private function updateTimeLastLogin()
	{
		global $cosa, $db;
		$sql = "UPDATE ".$db->table('users')." SET time_lastlogin = '".date("Y-m-d H:i:s")."' WHERE id='".$this->_data['id']."'";
		mysql_query($sql);
	}
	
	
	/**
	 * Check if user is logged in
	 * 
	 * @return	bool
	 */
	
	public function isLoggedIn() {
		return $this->_loggedIn;
	}
	
	
	/**
	 * Get user language
	 * 
	 * @return	string
	 */
	
	public function language() {
		return $this->_data['language'];
	}
	
	
	/**
	 * Check if uname exists in database
	 * 
	 * @param	string		$uname
	 * @return	bool
	 */
	
	public function unameExists($uname) {
		global $cosa, $db;
		$sql = "SELECT id FROM ".$db->table('users')." WHERE uname = '".addslashes($uname)."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->kill('Database error in the user library.', 'db');
		return (mysql_num_rows($res)) ? true : false;
	}
	
	
	/**
	 * Log out
	 * 
	 * @return	void
	 */
	
	public function logout()
	{
		$this->_loggedIn = false;
		$this->_data = array();
		$_SESSION[$this->_sessionName] = '';
	}
	
	
	/**
	 * Get user modules
	 * 
	 * @param	int		$group_id
	 * @return	array
	 */
	
	public function getModules($group_id)
	{
		// settings
			global $cosa, $db;
			$modules = array();
			if(!$group_id) $group_id = $this->_data['group_id'];
		
		// get user (group) modules
			$sql = "SELECT	m.* FROM ".$db->table('modules')." m, ".$db->table('modules_perm')." p WHERE m.id = p.module_id AND p.users_group_id = '".$group_id."'";
			$res = mysql_query($sql) or $cosa->kill('Could not get user modules.', 'db');
		
		// return modules
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) $modules[$row['path']] = $row;
			return $modules;
		
	}
	
	
	/**
	 * Get user (group) languages
	 * 
	 * @param	int		$group_id
	 * @param	bool	$cached
	 * @return	array
	 */
	
	public function getLanguages($group_id=false, $cached=true)
	{
		// required
			global $cosa, $db;
			if(is_array($this->_allowedLanguages) && $cached) return $this->_allowedLanguages;
			$data = array();
			if(!$group_id) $group_id = $this->_data['group_id'];
		
		// get user (group) languages
			$sql = "SELECT	l.* FROM ".$db->table('languages')." l, ".$db->table('languages_perm')." p WHERE l.id = p.language_id AND p.users_group_id = '".addslashes($group_id)."'";
			$res = mysql_query($sql) or $cosa->kill('Could not get user languages.', 'db');
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
				$data[stripslashes($row['id'])] = $row;
				if(!isset($defaultId)) $defaultId = stripslashes($row['id']);
			}
		
		// return data
			$this->defaultLanguage = $defaultId;
			$this->_allowedLanguages = $data;
			return $data;
		
	}
	
	
	/**
	 * Get the link to the user detail page
	 * 
	 * @param	int		$uid
	 * @param	bool	$html
	 * @return	string
	 */
	
	public function authorLink($uid=false, $html=true)
	{
		global $cosa;
		$user_id = ($uid) ? $uid : $this->_data['id'];
		$link = $cosa->system('base-url').'/?m=users&edit='.$user_id;
		return ($html) ? '<a href="'.$link.'">'.$this->getUname($uid).'</a>' : $link;
	}
	
	
	/**
	 * Get the uname
	 * 
	 * @param	int		$uid
	 * @return	string
	 */
	
	public function getUname($uid=false)
	{
		if($uid) return $this->_getUserDataFromDb('uname', $uid);
		else return $this->_data['uname'];
	}
	
	
	/**
	 * Get the (full) name
	 * 
	 * @param	int		$uid
	 * @param	bool	$full
	 * @return	string
	 */
	
	public function getName($uid=false, $full=true)
	{
		// get name
			if($uid) {
				$name_f = $this->_getUserDataFromDb('name_f', $uid);
				$name_l = $this->_getUserDataFromDb('name_l', $uid);
			} else {
				$name_f = $this->_data['name_f'];
				$name_l = $this->_data['name_l'];
			}
		
		// do some validation
			$name = ($full) ? $name_f.' '.$name_l : $name_f;
			$name = trim($name);
			$name = (empty($name)) ? $this->_data['uname'] : $name;
			return $name;
		
	}
	
	
	/**
	 * Get data from the users db
	 * 
	 * @param	string		$get
	 * @param	int			$user_id
	 * @return	string
	 */
	
	private function _getUserDataFromDb($get, $user_id)
	{
		global $cosa, $db;
		$sql = "SELECT ".addslashes($get)." AS r FROM ".$db->table('users')." WHERE id = '".addslashes($user_id)."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->kill('Could not fetch '.$get.' from users.', 'db');
		if(!mysql_num_rows($res)) return false;
		$user = mysql_fetch_array($res);
		return stripslashes($user['r']);
	}
	
	
	/**
	 * Update group permissions for modules
	 * 
	 * @param	int		$group_id
	 * @param	array	$new_perm
	 * @return	bool
	 */
	
	public function updateGroupModulePermissions($group_id, $new_perm)
	{
		// required
			global $cosa, $db;
		
		// check new_perm
			if(!is_array($new_perm)) return false;
		
		// delete current permissions
			$sql = "DELETE FROM ".$db->table('modules_perm')." WHERE users_group_id = '".addslashes($group_id)."'";
			mysql_query($sql) or $cosa->oops('Error while updating group permissions (A1).', 'db');
		
		// insert new permissions
			if(!empty($new_perm)) {
				$sql = "INSERT INTO `".$db->table('modules_perm')."` VALUES ";
				foreach($new_perm as $k => $id) $sql .= "('".addslashes($id)."', '".addslashes($group_id)."'), ";
				$sql = substr($sql, 0, strlen($sql)-2);
				mysql_query($sql) or $cosa->oops('Error while updating group permissions (A2).', 'db');
			}
		
		// return bool
			return true;
		
	}
	
	
	/**
	 * Update group permissions for languages
	 * 
	 * @param	int		$group_id
	 * @param	array	$new_perm
	 * @return	bool
	 */
	
	public function updateGroupLanguagePermissions($group_id, $new_perm)
	{
		// required
			global $cosa, $db;
		
		// check new_perm
			if(!is_array($new_perm)) return false;
		
		// delete current permissions
			$sql = "DELETE FROM ".$db->table('languages_perm')." WHERE users_group_id = '".addslashes($group_id)."'";
			mysql_query($sql) or $cosa->oops('Error while updating group permissions (B1).', 'db');
		
		// insert new permissions
			if(!empty($new_perm)) {
				$sql = "INSERT INTO `".$db->table('languages_perm')."` VALUES ";
				foreach($new_perm as $k => $id) $sql .= "('".addslashes($id)."', '".addslashes($group_id)."'), ";
				$sql = substr($sql, 0, strlen($sql)-2);
				mysql_query($sql) or $cosa->oops('Error while updating group permissions (B2).', 'db');
			}
		
		// return bool
			return true;
		
	}
	
	
	/**
	 * Check if user has permission to use specific language
	 * 
	 * @param	int		$language_id
	 * @return	bool
	 */
	
	public function hasLangPermission($language_id=false)
	{
		if(empty($language_id)) return false;
		return key_exists($language_id, $this->getLanguages());
	}
	
	
	/**
	 * Check if user has permission to edit
	 * 
	 * @return	bool
	 */
	
	public function hasEditPerm()
	{
		// @todo: make it work!
		return true;
	}
	
	
	/**
	 * Check if user has permission to delete
	 * 
	 * @return	bool
	 */
	
	public function hasDelPerm()
	{
		// if you can edit, you can delete
		return $this->hasEditPerm();
	}
	
	
	/**
	 * Check if user has permission to add
	 * 
	 * @return	bool
	 */
	
	public function hasAddPerm()
	{
		// @todo: make it work!
		return true;
	}
	
	
}


?>